package network.tcp;
/**
 * 问题
 * 1.flush
 * 2.close
 * 3.服务器支持多个客户端(多线程)
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;//相当于接客的前台
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService pool = Executors.newCachedThreadPool();
        while (true){
            //TCP有连接,需要客户端发起通信,通过accept方法"接听"(相当于拨号中的响铃过程)
            //(点击接听)没有客户端连过来,就会阻塞
            Socket clientSocket = serverSocket.accept();//相当于招待客户的服务员
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);//如果客户端较多,频繁创建销毁线程开销就会很大,此时引入线程池
                }
            });
        }
    }
    public void processConnection(Socket clientSocket){
        System.out.printf("[%s:%d] 客户端上线!\n",clientSocket.getInetAddress(),clientSocket.getPort());
        //循环读取客户端的请求并进行响应
        try (InputStream inputStream = clientSocket.getInputStream();
        OutputStream outputStream = clientSocket.getOutputStream()){

            while (true){
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){//阻塞等待请求,电话接通了,没人说话
                    //读取完毕,客户端断开连接
                    System.out.printf("[%s:%d] 客户端下线!\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //1.读取请求并解析. 这里暗藏着约定.next读的时候要读到空白符才算结束.
                //  因此就要求客户端发来的请求必须带有空白符结尾,比如\n或者空格.
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //outputStream.write(response.getBytes(),0,response.getBytes().length);
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req: %s,resp: %s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try{
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    public String process(String request) {
        return request;//请求是什么,响应就是什么
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }

}
